package com.atguigu.gmall.seckill.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * projectName: gmall
 *
 * @author: 陈鹏
 * time: 2022/10/18 19:00 星期二
 * description: 用于商品活动结束后同步商品库存到数据库的延迟队列配置
 */
@Configuration
public class SeckillGoodsDelayRabbitConfig {

    /**
     * 延迟队列的正常交换机
     * @return
     */
    @Bean("seckillGoodsDelayNormalExchange")
    public Exchange seckillGoodsDelayNormalExchange(){
        return ExchangeBuilder.directExchange("seckill_goods_delay_normal_exchange").build();
    }

    /**
     * 延迟队列的死信队列
     * @return
     */
    @Bean("seckillGoodsDelayDeadQueue")
    public Queue seckillGoodsDelayDeadQueue(){
        return QueueBuilder.durable("seckill_goods_delay_dead_queue")
                .withArgument("x-dead-letter-exchange","seckill_goods_delay_dead_exchange")
                .withArgument("x-dead-letter-routing-key","seckill.goods.normal")
                .build();
    }

    /**
     * 死信队列和正常交换机绑定
     * @param seckillGoodsDelayNormalExchange
     * @param seckillGoodsDelayDeadQueue
     * @return
     */
    @Bean("seckillGoodsDelayDeadBinding")
    public Binding seckillGoodsDelayDeadBinding(@Qualifier("seckillGoodsDelayNormalExchange") Exchange seckillGoodsDelayNormalExchange,
                                                @Qualifier("seckillGoodsDelayDeadQueue") Queue seckillGoodsDelayDeadQueue){
        return BindingBuilder.
                bind(seckillGoodsDelayDeadQueue).
                to(seckillGoodsDelayNormalExchange).
                with("seckill.goods.dead")
                .noargs();
    }

    /**
     * 延迟队列的死信交换机
     * @return
     */
    @Bean("seckillGoodsDelayDeadExchange")
    public Exchange seckillGoodsDelayDeadExchange(){
        return ExchangeBuilder.directExchange("seckill_goods_delay_dead_exchange").build();
    }

    /**
     * 延迟队列的正常队列
     * @return
     */
    @Bean("seckillGoodsDelayNormalQueue")
    public Queue seckillGoodsDelayNormalQueue(){
        return QueueBuilder.durable("seckill_goods_delay_normal_queue").build();
    }

    /**
     * 死信交换机和正常队列绑定
     * @param seckillGoodsDelayDeadExchange
     * @param seckillGoodsDelayNormalQueue
     * @return
     */
    @Bean
    public Binding seckillGoodsDelayNomalBinding(@Qualifier("seckillGoodsDelayDeadExchange") Exchange seckillGoodsDelayDeadExchange,
                                                 @Qualifier("seckillGoodsDelayNormalQueue") Queue seckillGoodsDelayNormalQueue){
        return BindingBuilder
                .bind(seckillGoodsDelayNormalQueue)
                .to(seckillGoodsDelayDeadExchange)
                .with("seckill.goods.normal")
                .noargs();
    }
}
